package com.itheima.project.adapter.impl;

import com.itheima.project.adapter.JsapiPayAdapter;
import com.itheima.project.config.ShowApiConfig;
import com.itheima.project.constant.trade.TradingCacheConstant;
import com.itheima.project.constant.trade.TradingConstant;
import com.itheima.project.core.enums.trade.TradingEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.handler.JsapiPayHandler;
import com.itheima.project.handler.NativePayHandler;
import com.itheima.project.pojo.Trading;
import com.itheima.project.service.ITradingService;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.ExceptionsUtil;
import com.itheima.project.utils.RegisterBeanHandler;
import com.itheima.project.vo.trade.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName JsapiPayAdapterImpl.java
 * @Description jsapi支付适配接口定义实现
 */
@Slf4j
@Component
public class JsapiPayAdapterImpl implements JsapiPayAdapter {

    @Autowired
    ITradingService tradingService;

    @Autowired
    RegisterBeanHandler registerBeanHandler;

    @Autowired
    RedissonClient redissonClient;

    private static Map<String,String> jsapiPayHandlers =new HashMap<>();

    static {
        jsapiPayHandlers.put(TradingConstant.TRADING_CHANNEL_ALI_PAY,"aliJsapiPayHandler");
        jsapiPayHandlers.put(TradingConstant.TRADING_CHANNEL_WECHAT_PAY,"wechatJsapiPayHandler");
    }


    @Override
    public TradingVo createJsapiTrading(TradingVo tradingVo) {
        //1、对交易订单加锁
        Long productOrderNo = tradingVo.getProductOrderNo();
        String key = TradingCacheConstant.CREATE_PAY + productOrderNo;
        RLock lock = redissonClient.getFairLock(key);
        try {
            boolean flag = lock.tryLock(TradingCacheConstant.REDIS_WAIT_TIME, TimeUnit.SECONDS);
            if (flag){
                //2、从IOC容器中找到NativePayHandler实现
                String nativePayHandlerString = jsapiPayHandlers.get(tradingVo.getTradingChannel());
                JsapiPayHandler jsapiPayHandler = registerBeanHandler
                        .getBean(nativePayHandlerString, JsapiPayHandler.class);
                //3、Native支付交易处理
                TradingVo downLineTrading = jsapiPayHandler.createJsapiTrading(tradingVo);
                return downLineTrading;
            }else {
                throw new ProjectException(TradingEnum.NATIVE_PAY_FAIL);
            }
        } catch (Exception e) {
            log.error("统一jsapi交易预创建建异常:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.NATIVE_PAY_FAIL);
        }finally {
            //释放锁
            lock.unlock();
        }
    }
}
